const {
  rootUrl,
  routeWithToken,
  to,
  openLoading,
  closeLoading
} = getApp()
const {
  getAssetsByScanQrCodeId
} = require('../../api/assets')

const {
  checkToken
} = require('../../api/checkToken')

const {
  getUserType
} = require('../../utils/strorage')

const {
  USER_TYPE
} = require('../../constant/index')

Page({
  data: {
    USER_TYPE,
    isReady: false
  },

  onLoad() {
    this.checkTokenIsOverdue();
  },

  async checkTokenIsOverdue() {
    openLoading()
    const [err] = await to(checkToken({}));
    closeLoading()

    if (!err) {
      wx.nextTick(() => {
        this.setData({
          isReady: true,
          userType: getUserType(),
        })
  
        const type = this.options.type
        if (type === 'scan') {
          this.handleScanCodeClick();
        }
      })
    }
  },

  handleRepairClick() {
    const self = this;
    wx.showActionSheet({
      itemList: ['扫码快速报修', '手动报修'],
      success(res) {
        switch (res.tapIndex) {
          case 0:
            self.handleScanCodeClick();
            break;
          case 1:
            self.handleToGoRepairPage()
        }
      }
    })
  },


  handleScanCodeClick() {
    wx.scanCode({
      onlyFromCamera: true,
      success: (res) => {
        this.getDeviceInfo(res.result)
      },
      fail: (err) => {
        console.log(err)
      }
    });
  },

  handleMenuIconClick(event) {
    const item = event.detail
    switch (item.key) {
      case 'repair': {
        if (item.route) {
          routeWithToken('/page-common/repair-page/index')
        } else if (item.type === 'both') {
          this.handleRepairClick()
        } else {
          this.handleScanCodeClick()
        }
        break;
      }
      default:
        this.handleRouteGo(event.detail)
        break;
    }
  },

  handleRouteGo(data) {
    routeWithToken(rootUrl(data.route + '/index'))
  },

  handleToGoRepairPage(code = '') {
    routeWithToken('/page-common/repair-page/index?qrCode=' + code)
  },

  getQrCode(code) {
    const list = code.split('/')
    return list[list.length - 1]
  },

  async getDeviceInfo(code) {
    const params = {
      qrCodeId: this.getQrCode(code)
    }
    openLoading()
    const [err, data] = await to(getAssetsByScanQrCodeId(params))
    closeLoading()
    if (!err) {
      wx.setStorageSync('device-manager', JSON.stringify(data))
      routeWithToken('/page-repair/device-manager/device-form/index?type=review&isscan=true&code=' + code)
    }
  }
})